import React, { useState } from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(err, errInfo) {
    // 你同样可以将错误日志上报给服务器
    const error = err.toString();
    const componentStack = errInfo.componentStack;
    console.log(`
    组件渲染错误
    错误信息: ${error}
    错误堆栈：${componentStack}
    `);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

const ErrorDiv = () => {
  const [num, setNum] = useState(0);

  if (num >= 3) {
    throw new Error(" this is error");
  }

  return (
    <div>
      <button
        onClick={() => {
          setNum((v) => v + 1);
        }}
      >
        button-{num}
      </button>
    </div>
  );
};

export default () => (
  <ErrorBoundary>
    <ErrorDiv />
  </ErrorBoundary>
);
